package chain;

import java.util.ArrayList;
import java.util.List;

/**
 * request
 */
class Request{
    public String name = "request";
}

/**
 * response
 */
class Response{
    public String name = "response";
}

/**
 * Filter
 */
@FunctionalInterface
interface FilterNew{
    void doFilter(Request request, Response response, FilterChain filterChain);
}

/**
 * FilterChain
 */
class FilterChain implements FilterNew{
    // 拿到所有的过滤器
    private List<FilterNew> list = new ArrayList<>();

    // 添加
    public FilterChain add(FilterNew filterNew){
        list.add(filterNew);
        return this;
    }

    // 获取
    private int flg = 0;
    public FilterNew getFilter(){
        try {
            return list.get(flg++);
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        FilterNew filterNew = getFilter();

        if(null != filterNew){
            filterNew.doFilter(request, response, filterChain);
        }
    }
}

/**
 * 责任链
 */
public class ChainOfResibility {
    public static void main(String[] args) {
        // create request
        Request request = new Request();
        // create response
        Response response = new Response();

        // 创建链调
        FilterChain filterChain = new FilterChain();
        filterChain.add((req, res, filterChainSm)->{
            System.out.println("先处理request01");
            // 根据条件判断是否继续向下执行
            filterChainSm.doFilter(req, res, filterChainSm);
            // 完事要处理response
            System.out.println("处理response01");
        }).add((req, res, filterChainSm)->{
            System.out.println("先处理request02");
            // 根据条件判断是否继续向下执行
            filterChainSm.doFilter(req, res, filterChainSm);
            // 完事要处理response
            System.out.println("处理response02");
        });

        // group2
        FilterChain filterChain1 = new FilterChain();
        filterChain1.add((req, res, filterChainSm)->{
            System.out.println("group2先处理request01");
            // 根据条件判断是否继续向下执行
            filterChainSm.doFilter(req, res, filterChainSm);
            // 完事要处理response
            System.out.println("group2处理response01");
        });

        filterChain.add(filterChain1);

        filterChain.doFilter(request, response, filterChain);
    }
}
